package com.smartkey.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.IBinder;
import android.util.Log;

import com.smartkey.receiver.BootReceiver;
import com.smartkey.receiver.MediaButtonReceiver;

public class BootService extends Service {

	private static final String TAG = "BootService";

	private MediaButtonReceiver mediaButtonReceiver;

	// private RotationObserver mRotationObserver;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "bootService started...");
		// if (mRotationObserver == null) {
		// // 创建观察类对象
		// mRotationObserver = new RotationObserver(this, new Handler());
		// }
		// //注册观察变化
		// mRotationObserver.startObserver();
		try {
			unregisterMediaButtonReceiver();
		} catch (Exception e) {
			e.printStackTrace();
		}
		registerMediaButtonReceiver();
		return super.onStartCommand(intent, flags, startId);
	}

	/**
	 * 耳机按键监听注册
	 */
	private void registerMediaButtonReceiver() {

		AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

		mediaButtonReceiver = new MediaButtonReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("android.intent.action.MEDIA_BUTTON");
		intentFilter.addCategory("android.intent.category.DEFAULT");
		intentFilter.setPriority(2147483647);
		registerReceiver(mediaButtonReceiver, intentFilter);
		mAudioManager.registerMediaButtonEventReceiver(new ComponentName(
				getPackageName(), MediaButtonReceiver.class.getName()));

	}

	/**
	 * 耳机按键监听解除注册
	 */
	private void unregisterMediaButtonReceiver() {
		if (mediaButtonReceiver != null) {
			unregisterReceiver(mediaButtonReceiver);
			AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
			mAudioManager.unregisterMediaButtonEventReceiver(new ComponentName(
					getPackageName(), MediaButtonReceiver.class.getName()));
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// 重新启动该service
		Intent intent = new Intent(BootReceiver.ACTION_RUNBACK);
		sendBroadcast(intent);
	}
}
